package models;

import controllers.GameController;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.node.ObjectNode;
import play.libs.F;
import play.libs.F.Callback;
import play.libs.F.Callback0;
import play.mvc.WebSocket;

/**
 * Created with IntelliJ IDEA.
 * User: chlemke
 * Date: 21.01.14
 * Time: 17:50
 * To change this template use File | Settings | File Templates.
 */
public class GameWebSocket extends WebSocket<JsonNode> {


    private GameConnection gameConnection;
    private final GameController gameController;
    private play.mvc.WebSocket.Out<JsonNode> out;
    private play.mvc.WebSocket.In<JsonNode> in;

    public GameWebSocket(GameConnection gameConnection, GameController gameController) {
        super();
        this.gameConnection = gameConnection;
        this.gameController = gameController;

    }

    @Override
    public void onReady(play.mvc.WebSocket.In<JsonNode> in, play.mvc.WebSocket.Out<JsonNode> out) {
          in.onMessage(new Callback<JsonNode>(){

              @Override
              public void invoke(JsonNode node) throws Throwable {
                 System.out.println(node);
                 String kind = node.get("kind").asText();

                 if(kind.equals("Command")){
                    String command = node.get("command").asText();
                           switch (command){
                        case "NextWave":
                            gameController.nextWave();
                            break;
                        case "UpdateTower":
                            gameController.updateTower(node.get("posx").asInt(), node.get("posy").asInt());
                            break;
                        case "BuildTower":
                            gameController.buildTower(node.get("posx").asInt(), node.get("posy").asInt(), node.get("towersize").asInt());
                            break;
                    }
                 }
            }
        });

        in.onClose(new Callback0() {
            @Override
            public void invoke() throws Throwable {
                // TODO close
                // GameWebSocket.this.gameController.removeObserver(GameWebSocket.this);
                closeConnection();
            }
        });

        this.out = out;
        this.in = in;

        gameConnection.gameConnectionReady();
    }

    public synchronized void send(ObjectNode message){

        out.write(message);
    }

    public void closeConnection(){
        out.close();
        in.onClose(new F.Callback0() {
            @Override
            public void invoke() throws Throwable {
                System.out.println("closeConnection() TODO");
                gameController.wuiTimer.cancel();
            }
        });
    }

}
